package me.zk.practice1.s;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Stack;

public class LS394 {
    public String decodeString(String s) {
        LinkedList<String> stk = new LinkedList<>();
        int index = 0;
        while (index < s.length()) {
            char cur = s.charAt(index);
            if (Character.isDigit(cur)) {
                StringBuffer sb = new StringBuffer();
                while (Character.isDigit(s.charAt(index))) {
                    sb.append(s.charAt(index++));
                }

                stk.addLast(sb.toString());
            } else if (Character.isLetter(cur) || cur =='[') {
                stk.addLast(String.valueOf(s.charAt(index++)));
            } else {
                ++index;
                LinkedList<String> sub = new LinkedList<>();
                while (!"[".equals(stk.peekLast())) {
                    sub.addLast(stk.removeLast());
                }
                Collections.reverse(sub);
                stk.removeLast();
                int rep = Integer.parseInt(stk.removeLast());
                StringBuffer t = new StringBuffer();
                String o = getString(sub);
                while (rep-- > 0) {
                    t.append(o);
                }
                stk.addLast(t.toString());
            }
        }
        return getString(stk);
    }
    public String getString(LinkedList<String> v) {
        StringBuffer ret = new StringBuffer();
        for (String s : v) {
            ret.append(s);
        }
        return ret.toString();
    }

    public static void main(String[] args) {
        LS394 l = new LS394();
        System.out.println(l.decodeString("3[adrfg]2[bc]"));
    }

}
